import jwt
from datetime import datetime, timedelta
from django.conf import settings
from django.http import JsonResponse

def generate_token(user_id):
    """
    生成JWT token
    :param user_id: 用户ID
    :return: token字符串
    """
    payload = {
        'user_id': user_id,
        'exp': datetime.utcnow() + timedelta(days=7)  # token有效期7天
    }
    token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
    return token

def verify_token(token):
    """
    验证JWT token
    :param token: token字符串
    :return: 成功返回user_id，失败返回None
    """
    try:
        if not token:
            return None
        # 如果token以Bearer 开头，去掉这个前缀
        if token.startswith('Bearer '):
            token = token[7:]
        payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
        return payload.get('user_id')
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None 